<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use app\BaseController;
use think\facade\View;
use app\middleware\CheckLogin;
use app\model\SalesOrder as OrderModel;
use app\model\SettingUser as UserModel;
use app\model\SettingCar as CarModel;
use app\model\SalesStock as StockModel;
use app\model\ServiceCustomer as CustomerModel;
use PHPExcel_IOFactory;

class Order extends BaseController
{
    // 注册控制器中间件
    protected $middleware = [CheckLogin::class];

    //主页
    public function index()
    {
        return redirect((string)url('Order/undelivered'));
    }

    /**
     * 显示未交订单列表
     *
     * @return \think\Response
     */
    public function undelivered()
    {
        //获取此前数据
        $data = OrderModel::where('state',1)->where('perfected',1)->select();

        // //查询是否有车
        for ($i=0; $i < count($data); $i++) { 
            //获取传递来的信息
            $where['vehicle'] = $data[$i]['vehicle'];
            $where['config'] = $data[$i]['config'];
            $where['color'] = $data[$i]['color'];
            $where['trim'] = $data[$i]['trim'];
            //查询是否有车
            $stockQuery = StockModel::where($where)->count();
            if($stockQuery > 0){
                $data[$i]['canDistribution'] = 1;
            }else{
                $data[$i]['canDistribution'] = 0;
            }
        }

        View::assign('data',$data);

        return view('undelivered');
    }

        /**
     * 未完善的订单列表.
     *
     * @return \think\Response
     */
    public function unperfected()
    {
        //获取此前数据
        $data = OrderModel::where('state',1)->where('perfected',0)->select();

        // //查询是否有车
        for ($i=0; $i < count($data); $i++) { 
            //获取传递来的信息
            $where['vehicle'] = $data[$i]['vehicle'];
            $where['config'] = $data[$i]['config'];
            $where['color'] = $data[$i]['color'];
            $where['trim'] = $data[$i]['trim'];
            //查询是否有车
            $stockQuery = StockModel::where($where)->count();
            if($stockQuery > 0){
                $data[$i]['canDistribution'] = 1;
            }else{
                $data[$i]['canDistribution'] = 0;
            }
        }

        View::assign('data',$data);

        return view('unperfected');
    }

    /**
     * 显示未交订单列表
     *
     * @return \think\Response
     */
    public function past()
    {
        //获取此前数据
        $data = OrderModel::where('state','<>',1)->select();

        View::assign('data',$data);

        return view('past');
    }

     /**
     * 首页配车页面数据提供
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function undeliveredDistribution($id)
    {
        //获取当前车辆可配车辆信息
        $order = OrderModel::find($id);
        $where['vehicle'] = $order['vehicle'];
        $where['config'] = $order['config'];
        $where['color'] = $order['color'];
        $where['trim'] = $order['trim'];
        $stockOption = StockModel::where($where)->select();
        $data['stockOption'] = $stockOption;
        $data['id'] = $id;
        return json($data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //获取销售顾问数据
        $sales = UserModel::where('visible',1)->column('name');
        View::assign('sales',$sales);

        //获取车系数据
        $vehicleOption = CarModel::where('valid','1')->Distinct(true)->column('vehicle');
        View::assign('vehicleOption',$vehicleOption);

        //渲染页面
        return view('create');
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = request()->param();
        //如果选择了车架号，则将配车状态改为1
        if(!empty($data['vin'])){
            $data['distribution'] = 1;

            //设置库存车辆为配车状态
            $stock = StockModel::where('vin',$data['vin'])->find();
            $stock->mated = 1;
            $stock->phone = $data['phone'];
            $stock->save();
        }

        //自主创建的订单直接设置为已经完善
        $data['perfected'] = 1;
       
        $result = OrderModel::create($data);//调用create方法写入数据库

        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //获取此前数据
        $data = OrderModel::find($id);
        View::assign('data',$data);

        return view('read');
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        //获取此前数据
        $data = OrderModel::find($id);
        View::assign('data',$data);

        //获取销售顾问数据
        $sales = UserModel::where('visible',1)->column('name');
        View::assign('sales',$sales);

        //获取车系数据
        $vehicleOption = CarModel::where('valid','1')->Distinct(true)->column('vehicle');
        View::assign('vehicleOption',$vehicleOption);

        //获取配置数据
        $configOption = CarModel::where('valid','1')->where('vehicle',$data['vehicle'])->Distinct(true)->column('config');
        View::assign('configOption',$configOption);

        //确定当前车型
        $carWhere['vehicle'] = $data['vehicle'];
        $carWhere['config'] = $data['config'];

        //获取当前车型配置数据
        $carData = CarModel::where($carWhere)->find();
        if(!empty($carData)){
            //获取当前车型颜色数据
            $colorOption = explode(',',$carData['color']);
            View::assign('colorOption',$colorOption);

            //获取当前车型内饰数据
            $trimOption = explode(',',$carData['trim']);
            View::assign('trimOption',$trimOption);
        }else{
            $colorOption = '配置输入有误';
            View::assign('colorOption',$colorOption);
            $trimOption = '配置输入有误';
            View::assign('trimOption',$trimOption);
        }

        //获取当前车辆可配车辆信息
        $where['vehicle'] = $data['vehicle'];
        $where['config'] = $data['config'];
        $where['color'] = $data['color'];
        $where['trim'] = $data['trim'];
        $stockOption = StockModel::where($where)->select();
        View::assign('stockOption',$stockOption);

        //模式是完善还是编辑
        $type = $request->param('type');
        if($type == 'edit'){
            return view('edit'); 
        }else{
            return view('perfect'); 
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //获取数据
        $data = request()->param();
        //如果选择了车架号，则将配车状态改为1
        if(!empty($data['vin'])){
            $data['distribution'] = 1;
            //设置库存车辆为配车状态
            $stock = StockModel::where('vin',$data['vin'])->find();
            $stock->mated = 1;
            $stock->perfected = 1;
            $stock->phone = $data['phone'];
            $stock->save();
        }else{
            $data['distribution'] = 0;
            $order = OrderModel::find($id);
            if(!empty($order['vin'])){
                //设置库存车辆为配车状态
                $stock = StockModel::where('vin',$order['vin'])->find();
                $stock->mated = 0;
                $stock->phone = "";
                $stock->save();
            }
        }
        //更新数据
        if(!empty($data['model'])){
            $data['perfected'] = 1;
            $result = OrderModel::update($data);//调用create方法写入数据库
        }else{
            $result = OrderModel::update($data);//调用create方法写入数据库
        }
        
        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

        /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //删除
        $user = OrderModel::find($id);//删除id号
        $result = $user->delete();//确认删除结果，返回布尔值
        if($result){
            return "ok";//成功则返回OK
        }else{
            return "false";//失败则返回false
        }
    }

    /**
     * 配车
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function distribution(Request $request, $id)
    {
        $vin = $request->param('vin');

        $order = OrderModel::find($id);

        //查询此前订单是否已经配车
        if(!empty($order['vin'])){
            //库存车辆设置为未配车
            $stock = StockModel::where('vin',$order['vin'])->find();
            $stock->mated = 0;
            $stock->phone = "";
            $stock->save();
        }

        //将此订单的配车设置为1
        $order->distribution = 1;
        $order->vin = $vin;
        $result = $order->save();

        //库存车辆设置为配车
        $stock = StockModel::where('vin',$vin)->find();
        $stock->mated = 1;
        $stock->phone = $order['phone'];
        $stock->save();

        if($result){
            return 'ok';
        }else{
            return 'false';
        }
    }

    /**
     * 交车
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function deliver($id)
    {
        //订单状态设置为交车
        $order = OrderModel::find($id);
        $order->state = 2;
        $order->deliver_date = date('Y-m-d');
        $order_result = $order->save();
        $result = true;
        if(!$order_result){
            $result = false;
            $reason = '订单状态设置失败';
        }

        //库存车辆设置为交车
        $stock = StockModel::where('vin',$order['vin'])->find();
        $stock->deliver = 1;
        $stock->deliver_date = $order['deliver_date'];
        $stock_result = $stock->save();
        $result = true;
        if(!$stock_result){
            $result = false;
            $reason = '库存车辆交车状态设置失败';
        }

        /////////////////////////
        //传递参数给客服部
        $customer['deliver_date'] = $order['deliver_date'];//交车日期
        $customer['sales'] = $order['sales'];//销售顾问

        //根据车架号去查询车辆的信息
        $customer['vin'] = $stock['vin'];//车架号
        $customer['vehicle'] = $stock['vehicle'];//车系
        $customer['config'] = $stock['config'];//配置
        $customer['color'] = $stock['color'];//颜色
        $customer['trim'] = $stock['trim'];//内饰
        $customer['model'] = $stock['model'];//车系编码
        $customer['engine'] = $stock['engine'];//发动机号

        //成交信息
        $customer['final_price'] = $order['finalprice'];//最终成交价
        $customer['owner_name'] = $order['name'];//车主名称
        $customer['owner_phone'] = $order['phone'];//车主电话

        // 客户信息写入客服部数据库
        $customer_result = CustomerModel::create($customer);
        $result = true;
        if($customer_result == false){
            $result = false;
            $reason = '客服部信息传递失败';
        }
        //////////////////////////

        if($result){
            return 'ok';
        }else{
            return $reason;
        }
    }

    /**
     * 退单
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function chargeback($id)
    {
        $order = OrderModel::find($id);
        $order->state = 0;

        if(!empty($order['vin'])){
            //库存车辆设置为未配车
            $stock = StockModel::where('vin',$order['vin'])->find();
            $stock->mated = 0;
            $stock->phone = "";
            $stock->save();
        }

        $order->vin = "";
        $order->distribution = 0;
        $result = $order->save();
        if($result){
            return 'ok';
        }else{
            return 'false';
        }
    }

    /**
     * 批量模板导入数据的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */

    public function input(Request $request)
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('input-excel');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('tmp')->putFile('OrderExcel',$file);
        // //获取文件路径
        $path = public_path().'runtime/tmp/'.$savename;

        $objPHPExcel = PHPExcel_IOFactory::load($path,$encode = 'utf-8');
 
        $sheet = $objPHPExcel->getSheet(0)->toArray();

        // dump($sheet);
        //检查模板有没有问题
        if($sheet[0][3] != "客户电话" || $sheet[0][9] != "车型编号"){
            $return['result'] = false;
            $return['reason'] = '模板错误';
            $return['count'] = 0;
            $return['blankRow'] = 0;
        }else{
            $data = array();
            for ($i=1; $i < count($sheet); $i++) {
                $vin = $sheet[$i][9];
                //判断这一行是否有车架号信息
                $blankRow = 0;
                if(!empty($vin)){
                    //以车架号判断是否有重复的车辆信息
                    $old = StockModel::where('vin',$vin)->find();
                    if(empty($old)){
                        $data[$i]['create_date'] = date("Y-m-d",strtotime($sheet[$i][0]));
                        $data[$i]['sales'] = trim($sheet[$i][1]);
                        $data[$i]['name'] = trim($sheet[$i][2]);
                        $data[$i]['phone'] = trim($sheet[$i][3]);
                        $data[$i]['vehicle'] = trim($sheet[$i][4]);
                        $data[$i]['config'] = $sheet[$i][5];
                        $data[$i]['color'] = trim($sheet[$i][6]);
                        $data[$i]['trim'] = trim($sheet[$i][7]);
                        $data[$i]['option'] = trim($sheet[$i][8]);
                        $data[$i]['model'] = trim($sheet[$i][9]);
                        $data[$i]['price'] = trim($sheet[$i][10]);
                        $data[$i]['finalprice'] = trim($sheet[$i][11]);
                        $data[$i]['frontmoney'] = trim($sheet[$i][12]);
                        $data[$i]['state'] = trim($sheet[$i][13]);
                    }
                }else{
                    $blankRow = $blankRow + 1;
                }  
            }
            $user = new OrderModel;
            $saveResult = $user->saveAll($data);
            $return['count'] = count($saveResult);
            $return['result'] = true;
            $return['reason'] = '没有错误';
            $return['blankRow'] = $blankRow;
            
        }

        return json($return);
    }

    /**
     * 批量导出数据的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */

    public function undeliveredOutput()
    {
        //未交库存部分
        //获取还未交车的库存数据
        $data = OrderModel::where('state',1)->order('create_date','asc')->select();

        //创建PHPExcel对象
        $objPHPExcel = new \PHPExcel();

        //设置文件描述信息
        $objPHPExcel->getProperties()->setCreator('桂林灵川WEY'); //设置创建者
        $objPHPExcel->getProperties()->setLastModifiedBy(''); //设置修改者
        $objPHPExcel->getProperties()->setTitle('桂林灵川WEY未交订单表'); //设置标题
        $objPHPExcel->getProperties()->setSubject('桂林灵川WEY未交订单表'); //设置主题
        $objPHPExcel->getProperties()->setDescription(''); //设置描述
        $objPHPExcel->getProperties()->setKeywords('桂林灵川WEY未交订单表');//设置关键词
        $objPHPExcel->getProperties()->setCategory('');//设置类型

        // 设置当前sheet为第1页
        $objPHPExcel->setActiveSheetIndex(0);

        // 设置当前sheet的名称
        $objPHPExcel->getActiveSheet()->setTitle('未交订单表');

        // 列标
        $list = ['A', 'B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P'];

        // 设置第一行加粗和左对齐
        foreach ($list as $col) {
            
            //设置水平居中
            if($col != 'I'){
                $objPHPExcel->getActiveSheet()
                    ->getStyle($col)->getAlignment()
                    ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            }

            //设置垂真居中
            $objPHPExcel->getActiveSheet()
                ->getStyle($col)->getAlignment()
                ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            
            
            // 设置第一行加粗
            $objPHPExcel->getActiveSheet()->getStyle($col.'1')
                ->getFont()->setBold(true);

            //设置第一行背景颜色
            $objPHPExcel->getActiveSheet()->getStyle($col.'1')
                ->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)
                ->getStartColor()->setRGB('2f6921');//设置第一行背景色为ccffff
        }

        //逐行设置行高
        for ($i=1; $i < count($data)+2; $i++) { 
            //设置行高
            $objPHPExcel->getActiveSheet()->getRowDimension($i)->setRowHeight(30);
        }

        // 设置列宽
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);//订单时间
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(8);//销售顾问
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(8);//客户名称
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(14);//客户电话
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(8);//车型
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(22);//配置
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);//颜色
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);//内饰
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(16);//选装
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(14);//车型编码
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);//指导价
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(10);//成交价
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(10);//定金
        $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(7);//状态
        $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(9);//是否配车
        $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(21);//车架号

        // 填充第一行数据
        $objPHPExcel->getActiveSheet()
            ->setCellValue($list[0] . '1', '订单时间')
            ->setCellValue($list[1] . '1', '销售顾问')
            ->setCellValue($list[2] . '1', '客户名称')
            ->setCellValue($list[3] . '1', '客户电话')
            ->setCellValue($list[4] . '1', '车型')
            ->setCellValue($list[5] . '1', '配置')
            ->setCellValue($list[6] . '1', '颜色')
            ->setCellValue($list[7] . '1', '内饰')
            ->setCellValue($list[8] . '1', '选装')
            ->setCellValue($list[9] . '1', '车型编码')
            ->setCellValue($list[10] . '1', '指导价')
            ->setCellValue($list[11] . '1', '成交价')
            ->setCellValue($list[12] . '1', '定金')
            ->setCellValue($list[13] . '1', '状态')
            ->setCellValue($list[14] . '1', '是否配车')
            ->setCellValue($list[15] . '1', '车架号');

        // 设置数据
        // 定义一个i变量，目的是在循环输出数据是控制行数
        for ($i=0; $i < count($data); $i++) { 
            $mated = $data[$i]['distribution'] == 1?'是':'否';

            //当前行数
            $row = $i + 2;
            $objPHPExcel->getActiveSheet()
                ->setCellValue($list[0] . $row, date('Y/m/d',strtotime($data[$i]['create_date'])))
                ->setCellValue($list[1] . $row, $data[$i]['sales'])
                ->setCellValue($list[2] . $row, $data[$i]['name'])
                ->setCellValue($list[3] . $row, $data[$i]['phone'])
                ->setCellValue($list[4] . $row, $data[$i]['vehicle'])
                ->setCellValue($list[5] . $row, $data[$i]['config'])
                ->setCellValue($list[6] . $row, $data[$i]['color'])
                ->setCellValue($list[7] . $row, $data[$i]['trim'])
                ->setCellValue($list[8] . $row, $data[$i]['option'])
                ->setCellValue($list[9] . $row, $data[$i]['model'])
                ->setCellValue($list[10] . $row, $data[$i]['price'])
                ->setCellValue($list[11] . $row, $data[$i]['finalprice'])
                ->setCellValue($list[12] . $row, $data[$i]['frontmoney'])
                ->setCellValue($list[13] . $row, $data[$i]['state'])
                ->setCellValue($list[14] . $row, $mated)
                ->setCellValue($list[15] . $row, $data[$i]['vin']);
        }

        //数据导出
        ob_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=桂林长道WEY未交订单表.xlsx');
        header('Cache-Control: max-age=1');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $file = $objWriter->save('php://output');
        exit; //必须 终止
    }
}
